﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for LoginProcess
/// </summary>
public class LoginProcess
{
	public LoginProcess()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public bool UserValidate(string sCompanyID, string sUserID, string sUserPwd)
    {
        bool bRet = true;
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (HttpContext.Current.Session["servercon"] != null)
                if (HttpContext.Current.Session["servercon"].ToString() != "")
                    HDD = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
            string strWhere = "company_id='" + sCompanyID.Replace("'", "''") + "' and  user_id='" + sUserID.Replace("'", "''") + "'";

            string actual_password = security.decrypt(HDD.GetColumnValue("ngcompanyuser", "password", strWhere));
            bRet = (actual_password != "" && sUserPwd == actual_password);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("LoginProcess: UserValidate: Error: " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return bRet;
    }

    public string getCompanyHomePage(string sCompanyID, string sUserID, string sUserPwd)
    {
        string sRet = "";
        HDDatabase HDD = new HDDatabase();
        AuditLog AL = new AuditLog();
        HttpContext.Current.Session.Remove("dbcon");
        security hds = new security(sUserID);
        try
        {
            if (hds.SaaSUserAuthenticateNew(sCompanyID, sUserID))
            {
                HDDatabase hddb = new HDDatabase();
                DataTable dtUsertable = new DataTable(); string strUserFullName = ""; string strUserRole = ""; string strRoleId = ""; string strWelcomeTitle = "";
                dtUsertable = hddb.GetDataTable("select isnull(first_name,'') + ' ' + isnull(last_name,''),af_row_id,locale from sy_usr where user_id='" + sUserID.Replace("'", "''") + "'");
                if (dtUsertable != null)
                    if (dtUsertable.Rows.Count > 0)
                    {
                        strUserFullName = HttpUtility.HtmlEncode(dtUsertable.Rows[0][0].ToString());
                        HttpContext.Current.Session["userlocale"] = dtUsertable.Rows[0]["locale"].ToString();
                        DataRow drRole = hddb.GetTableRow("select af_row_id,role_name from sy_rol where af_row_id='" + hddb.GetColumnValue("select role_id from sy_usr_rol where user_id='" + dtUsertable.Rows[0][1].ToString() + "'") + "'");
                        if (drRole != null)
                        {
                            strRoleId = drRole["af_row_id"].ToString();
                            strUserRole = drRole["role_name"].ToString();
                        }
                    }
                HttpContext.Current.Session["user_name"] = strUserFullName;
                HttpContext.Current.Session["user_role"] = strUserRole;
                HttpContext.Current.Session["userid"] = sUserID;
                HttpContext.Current.Session["roleid"] = strRoleId;

                string sTheme = "";
                DataTable dtUser = hddb.GetDataTable("select * from sy_usr");
                if (dtUser.Columns.Contains("theme"))
                {
                    DataRow[] drr = dtUser.Select("user_id='" + sUserID.Replace("'", "''").Trim() + "'");
                    if (drr.Length > 0)
                    {
                        sTheme = drr[0]["theme"].ToString().Trim();
                        HttpContext.Current.Session["user_afrowid"] = dtUser.Columns.Contains("af_row_id") == true ? drr[0]["af_row_id"].ToString() : HttpContext.Current.Session["userid"].ToString();//included by sanal
                        HttpContext.Current.Session["custodian"] = drr[0]["custodian_filter"].ToString();
                    }
                }

                strWelcomeTitle = CommonFunctions.replaceSystemVariables(hddb.getAcrMemValue("c5016bbf3100ab6f", "WT")); // Added by 'Imran Gani' on 24-Dec-2012, for dynamic welcome title.
                HttpContext.Current.Session["Welcome_Title"] = strWelcomeTitle;

                if (sTheme == "")
                    HttpContext.Current.Session["Theme"] = GlobalValues.DefaultTheme;
                else
                    HttpContext.Current.Session["theme"] = sTheme;
                AL.logUserInCompany();
                AL.logUserInModel(sCompanyID, sUserID, true);
                AL = null;
                //create logo file in server
                createCustomLogo();

                string sUrlContinue = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString["continue"] != null ? HttpContext.Current.Request.QueryString["continue"].ToString() : "");
                string msg_id = hddb.GetColumnValue("select af_row_id from sy_messages where active=1 order by modified_at desc;"); // Modified by 'Imran Gani' on 18-Jul-2013, to get recently modified data.
                if (msg_id != "")
                    sUrlContinue = "msg.aspx?id=" + msg_id + "&url=" + HttpUtility.UrlEncode((sUrlContinue != "" ? sUrlContinue : navigate2Home()));
                else
                    sUrlContinue = (sUrlContinue != "" ? sUrlContinue : navigate2Home());
                sRet = checkPasswordValidityPeriod(sUrlContinue, sUserPwd);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("LoginProcess: getCompanyHomePage: Error: " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return sRet;
    }

    private void createCustomLogo()
    {
        security s = new security();
        string fName = ""; string ext = "";
        if (s.createCustomLogo(ref fName, ref ext))
            HttpContext.Current.Session["hasCustomLogo"] = "1";
        else
            HttpContext.Current.Session["hasCustomLogo"] = "0";
        s = null;
    }
    private string navigate2Home()
    {
        Navigator ng = new Navigator();
        string retrn = ng.getUserHomePage();
        ng = null;
        return retrn;
    }
    
    /// <summary>
    /// To check Password Validity Period, when user login.
    /// </summary>
    /// <param name="sUrlContinue">URL to continue.</param>
    // Added by 'Imran Gani' on 25-Nov-2013.
    private string checkPasswordValidityPeriod(string sUrlContinue, string sUserPwd)
    {
        string sRet = sUrlContinue;
        HDDatabase hdd = new HDDatabase();
        DataTable dt_pwdSecurityLog = new DataTable();
        string sRecentPwdLogDate;
        try
        {
            string svalidity_period = hdd.GetColumnValue("select mem_value2 from sy_acr_mem where acr_id = '21597547e2b0fa68' and mem_id = 'validity_period' and af_row_id = 'a5cd5d2f7aa7fa0f' and mem_value1 = 'enabled';");
            if (string.IsNullOrEmpty(svalidity_period) || svalidity_period == "0")
                sRet = sUrlContinue;
            else
            {
                sRecentPwdLogDate = hdd.GetColumnValue("select [created_at] from [sy_password_security_log] where [applies_to] = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "' order by [created_at] desc;");
                if (string.IsNullOrEmpty(sRecentPwdLogDate))
                {
                    AuditLog AL = new AuditLog();
                    AL.WritePasswordSecurityLog(HttpContext.Current.Session["user_afrowid"].ToString(), HttpContext.Current.Session["user_afrowid"].ToString(), security.encrypt(sUserPwd), "Initiated log");
                    AL = null;
                    sRet = sUrlContinue;
                }
                else
                {
                    DateTime RecentLogCreatedAt = Convert.ToDateTime(sRecentPwdLogDate);
                    DateTime CurrentDate = DateTime.Now.ToUniversalTime();
                    TimeSpan difference = CurrentDate.Subtract(RecentLogCreatedAt);
                    int TotalDays = Convert.ToInt32(difference.TotalDays);
                    if (TotalDays < Convert.ToInt32(svalidity_period))
                        sRet = sUrlContinue;
                    else
                    {
                        sRet = "changepassword.aspx?mn=bc98f78ad064743a&pgs_id=335dea653698e7a7&c_url=" + HttpUtility.UrlEncode(sUrlContinue) + "&ViewMode=content";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Default: checkPasswordValidityPeriod: Error: " + ex.Message);
        }
        finally
        {
            dt_pwdSecurityLog.Dispose();
        }
        return sRet;
    }
}